package com.nostop.service;

import com.google.common.base.Preconditions;
import com.nostop.common.RequestHolder;
import com.nostop.exception.ParamException;
import com.nostop.mapper.SysRoleMapper;
import com.nostop.model.SysRole;
import com.nostop.param.RoleParam;
import com.nostop.util.BeanValidator;
import com.nostop.util.IpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    public void save(RoleParam param){
        BeanValidator.checkParam(param);
        if (checkExist(param.getName(),param.getId())){
            throw new ParamException("角色名称已经存在");
        }
        SysRole sysRole = SysRole.builder().name(param.getName())
                .type(param.getType()).status(param.getStatus())
                .remark(param.getRemark()).build();
        sysRole.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysRole.setOperaterIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysRole.setOperaterTime(new Date());
        sysRoleMapper.insert(sysRole);
    }

    public void update(RoleParam param){
        BeanValidator.checkParam(param);
        BeanValidator.checkParam(param);
        if (checkExist(param.getName(),param.getId())){
            throw new ParamException("角色名称已经存在");
        }
        SysRole before = sysRoleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新的角色不存在");
        SysRole after = SysRole.builder().id(param.getId()).name(param.getName())
                .type(param.getType()).status(param.getStatus())
                .remark(param.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperaterIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperaterTime(new Date());
        sysRoleMapper.updateByPrimaryKeySelective(after);
    }

    public List<SysRole> getAll(){
        return sysRoleMapper.getAll();
    }

    private boolean checkExist(String name,Integer id) {
        return sysRoleMapper.CountByName(name,id) > 0;
    }
}
